//
//  MSHomeViewController.m
//  Cartoon
//
//  Created by yaren hunter on Height17/4/19.
//  Copyright © Height17年 yaren. All rights reserved.
//

#import "MSHomeViewController.h"
#import "Header.h"

@interface MSHomeViewController ()<UIScrollViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
//图片
@property (nonatomic,strong)NSMutableArray * imagesArr;
//定时器
@property (nonatomic,strong)NSTimer * timer;

//页码控制器
@property (nonatomic,strong)UIPageControl *pageControl;

//fistCollectViewDataSource
@property (nonatomic,strong)NSMutableArray * fDataSourceArr;
//secondCollectViewDataSource
@property (nonatomic,strong)NSMutableArray * sDataSourceArr;
//thirdCollectViewDataSource
@property (nonatomic,strong)NSMutableArray * tDataSourceArr;


@end

static NSString * const fid = @"fistCellId";
static NSString * const sid = @"secondCellId";
static NSString * const tid = @"thirdCellId";
#define PADDING 8

@implementation MSHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setImage];
    _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(action) userInfo:nil repeats:YES];
    self.navigationController.navigationBar.translucent = NO;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewDidAppear:(BOOL)animated{
    [self setContraints];
    [self setupScrollView];
    [super viewDidAppear:animated];
    int contenSizeY = CGRectGetMaxY(_thirdCollectionView.frame);
    [_backgroundScrollView setContentSize:CGSizeMake(self.view.frame.size.width,contenSizeY) ];
    [self setupCollectionView];
//
    
}


- (void)setupScrollView{
    _topScrollView.delegate = self;
    //是否自动裁切超出部分
    _topScrollView.clipsToBounds = YES;
    //设置是否可以缩放
    _topScrollView.scrollEnabled = YES;
    //设置是否可以进行画面切换
    _topScrollView.pagingEnabled = YES;
    
    [self topScrollViewSetImage];
}

- (void)setupPageControl{
    _pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
    [self.view addSubview:_pageControl];
    _pageControl.backgroundColor = [UIColor blackColor];
    _pageControl.alpha = 0.5;
    _pageControl.numberOfPages = _imagesArr.count;
    _pageControl.currentPage =0;
    [_pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_topScrollView.mas_left);
        make.bottom.equalTo(_topScrollView.mas_bottom);
        make.right.equalTo(_topScrollView.mas_right);
        make.height.equalTo(@20);
    }];
}
- (void)topScrollViewSetImage{
    self.imagesArr = [[NSMutableArray alloc]init];
    for (int i = 0; i<=4; i++) {
        NSString * imageName = [NSString stringWithFormat:@"girl0%d",i+1];
        UIImage * image = [UIImage imageNamed:imageName];
        [_imagesArr addObject:image];
    }
//    UIImage * image = [UIImage imageNamed:@"girl01"];
//    [_imagesArr addObject:image];
    
    
    NSUInteger pages = 0;
    NSInteger originX = 0;
    [self setupPageControl];
    for (UIImage * image in _imagesArr) {
        
        CGRect rect = _topScrollView.frame;
        rect.origin.x = originX;
        rect.origin.y = 0;
        rect.size.height = _topScrollView.frame.size.height;
        rect.size.width = _topScrollView.frame.size.width;
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:rect];
        imageView.image = image;
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        [_topScrollView addSubview:imageView];
        pages++;
        originX += _topScrollView.frame.size.width;
    }

    //设置滚动视图的位置
    [_topScrollView setContentSize:CGSizeMake(originX, _topScrollView.bounds.size.height)];
}

- (void)setContraints{
#define Padding 8
#define Height 20
   _backgroundScrollView.backgroundColor = [UIColor redColor];
    
    [_backgroundScrollView setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [_topScrollView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@150);
        make.right.equalTo(self.view.mas_right).offset(-Padding);
        make.top.equalTo(_backgroundScrollView.mas_top).offset(Padding);
        make.left.equalTo(self.view.mas_left).offset(Padding);
    }];

    /**
     推荐栏

     @param make ;
     @return ;
     */
    [_firsImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@Height);
        make.width.equalTo(@Height);
        make.left.equalTo(self.view.mas_left).offset(Padding);
        make.top.equalTo(_topScrollView.mas_bottom).offset(Padding);
        
    }];
    [_firstLabelView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_firsImageView.mas_right).offset(Padding);
        make.top.equalTo(_firsImageView.mas_top);
        make.height.equalTo(_firsImageView.mas_height);
        make.right.equalTo(_firstButton.mas_left).offset(-Padding);
    }];
    [_firstButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_firsImageView.mas_top);
        make.right.equalTo(_firstImageIView1.mas_left).offset(-Padding);
        make.height.equalTo(_firsImageView.mas_height);
        make.width.equalTo(@(2*Height));
    }];
    [_firstImageIView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_firsImageView.mas_top);
        make.right.equalTo(self.view).offset(-Padding);
        make.height.equalTo(_firsImageView.mas_height);
        make.width.equalTo(@Height);
    }];

    [_firstCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@100);
        make.left.equalTo(self.view).offset(Padding);
        make.right.equalTo(self.view).offset(-Padding);
        make.top.equalTo(_firsImageView.mas_bottom).offset(Padding);
    }];
    
    /**
     专题

     @param make ;
     @return <#return value description#>
     */
    [_secondImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@Height);
        make.width.equalTo(@Height);
        make.left.equalTo(self.view.mas_left).offset(Padding);
        make.top.equalTo(_firstCollectionView.mas_bottom).offset(Padding);
        
    }];
    [_secondLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_secondImageView.mas_right).offset(Padding);
        make.top.equalTo(_secondImageView.mas_top);
        make.height.equalTo(_secondImageView.mas_height);
        make.right.equalTo(_secondButton.mas_left).offset(-Padding);
    }];
    [_secondButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_secondImageView.mas_top);
        make.right.equalTo(_secondImageView1.mas_left).offset(-Padding);
        make.height.equalTo(_secondImageView.mas_height);
        make.width.equalTo(@(2*Height));
    }];
    [_secondImageView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_secondImageView.mas_top);
        make.right.equalTo(self.view).offset(-Padding);
        make.height.equalTo(_secondImageView.mas_height);
        make.width.equalTo(@Height);
    }];
    
    [_secondCollectionview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@100);
        make.left.equalTo(self.view).offset(Padding);
        make.right.equalTo(self.view).offset(-Padding);
        make.top.equalTo(_secondImageView.mas_bottom).offset(Padding);
    }];
    
    /**
     名家

     @param make <#make description#>
     @return <#return value description#>
     */
    [_thirdImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@Height);
        make.width.equalTo(@Height);
        make.left.equalTo(self.view.mas_left).offset(Padding);
        make.top.equalTo(_secondCollectionview.mas_bottom).offset(Padding);
        
    }];
    [_thirdLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_thirdImageView.mas_right).offset(Padding);
        make.top.equalTo(_thirdImageView.mas_top);
        make.height.equalTo(_thirdImageView.mas_height);
        make.right.equalTo(_thirdButton.mas_left).offset(-Padding);
    }];
    [_thirdButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_thirdImageView.mas_top);
        make.right.equalTo(_thirdImageView1.mas_left).offset(-Padding);
        make.height.equalTo(_thirdImageView.mas_height);
        make.width.equalTo(@(2*Height));
    }];
    [_thirdImageView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_thirdImageView.mas_top);
        make.right.equalTo(self.view).offset(-Padding);
        make.height.equalTo(_thirdImageView.mas_height);
        make.width.equalTo(@Height);
    }];
    
    [_thirdCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@100);
        make.left.equalTo(self.view).offset(Padding);
        make.right.equalTo(self.view).offset(-Padding);
        make.top.equalTo(_thirdImageView.mas_bottom).offset(Padding);
    }];
    [self.view layoutIfNeeded];
    
}

- (void)setImage{
    NSArray *imageArr = @[_firsImageView,_firstImageIView1,_secondImageView1,_secondImageView,_thirdImageView1,_thirdImageView];
    for (UIImageView * imageView in imageArr) {
        imageView.image = [UIImage imageNamed:@"girl04"];
    }
}

- (void)action{
#define WIDTH _topScrollView.frame.size.width
    float offsetX = _topScrollView.contentOffset.x;
    offsetX += WIDTH;
    if (offsetX >= _imagesArr.count * WIDTH) {
        offsetX = 0;
        
        [ _pageControl setCurrentPage:0];
        [_topScrollView setContentOffset:CGPointMake(0, 0) animated:NO];
//        [_topScrollView setContentOffset:CGPointMake(WIDTH, 0) animated:YES];
//        [ _pageControl setCurrentPage:1];
    }else{
        [_topScrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
       
        [_pageControl setCurrentPage:offsetX / WIDTH];
        
    }
    
}

- (void)setupCollectionView{
    _fDataSourceArr = [[NSMutableArray alloc]init];
//数据请求
    int i = 0;
    for (UIImage * image in _imagesArr) {
        NSString * labelText = [NSString stringWithFormat:@"%d",i];
        i++;
        MSCoverModel * model = [[MSCoverModel alloc]init];
        model.image = image;
        model.title = labelText;
        [_fDataSourceArr addObject:model];
    }
//
    _firstCollectionView.delegate = self;
    _firstCollectionView.dataSource = self;
    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc]init];
    _firstCollectionView.collectionViewLayout = flowLayout;
    float itemWidth = (self.view.bounds.size.width
                       - PADDING * 4) / 3;
    float itemHeight = itemWidth * 1.2;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.itemSize = CGSizeMake(itemWidth, itemHeight);
    flowLayout.minimumInteritemSpacing = PADDING / 2;
    flowLayout.minimumLineSpacing = PADDING / 2;
    [_firstCollectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(itemHeight + 1));// item的fram大于view的话会报错
        make.left.equalTo(self.view).offset(Padding);
        make.right.equalTo(self.view).offset(-Padding);
        make.top.equalTo(_firsImageView.mas_bottom).offset(Padding);
    }];
    _firstCollectionView.collectionViewLayout = flowLayout;
    [_firstCollectionView registerNib:[UINib nibWithNibName:@"MSCollectionViewCell"  bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:fid];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark -- 滚动视图的代理方法
//开始拖拽的代理方法，在此方法中暂停定时器。
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    NSLog(@"正在拖拽视图，所以需要将自动播放暂停掉");
    //setFireDate：设置定时器在什么时间启动
    //[NSDate distantFuture]:将来的某一时刻
    if ([scrollView isEqual:_topScrollView]) {
        [_timer setFireDate:[NSDate distantFuture]];
        int x =  _topScrollView.contentOffset.x / self.view.frame.size.width;
        [_pageControl setCurrentPage:x];
    }
    
    
}

//视图静止时（没有人在拖拽），开启定时器，让自动轮播
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    //视图静止之后，过1.5秒在开启定时器
    //[NSDate dateWithTimeInterval:1.5 sinceDate:[NSDate date]]  返回值为从现在时刻开始 再过1.5秒的时刻。
    if ([scrollView isEqual:_topScrollView]) {
        NSLog(@"开启定时器");
        [_timer setFireDate:[NSDate dateWithTimeInterval:2 sinceDate:[NSDate date]]];
    }
}

#pragma mark -- Collectionview代理方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if ([collectionView isEqual:_firstCollectionView]) {
        return _fDataSourceArr.count;
    }else if([collectionView isEqual:_secondCollectionview]){
        return 1;
    }else {
        return 1;
    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MSCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:fid forIndexPath:indexPath];
    MSCoverModel * model = _fDataSourceArr[indexPath.item];
    [cell updateCellWithModel:model];
    return cell;
}

@end
